﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using KC.ExtensionMethods;
using KC.DataAccess.MV6;

namespace KC.Business.Meta
{
	public static class Utils
	{
		/// <summary>Given a line from an IIS log, locates and returns the IP address if it exists.</summary>
		/// <param name="lineparts">String array consisting of the parts of a line from an IIS log file</param>
		/// <returns>IP address from that line</returns>
		public static string ExtractIPfromLogLine(string[] lineparts)
		{
			if (lineparts == null)
				throw new ArgumentNullException("lineparts", "Cannot extract IP from a null array");

			int DummyInt;
			string ipstr = null;
			foreach (string linepart in lineparts)
				if (int.TryParse(linepart.Replace(".", ""), out DummyInt) && linepart.CountOf('.') == 3)
					ipstr = linepart.Trim();
			return ipstr;
		}
		/// <summary>Processes a line for spiders</summary>
		/// <param name="line">Line from IIS log file</param>
		/// <returns>True if spider added; false if spider existed or if failure</returns>
		public static bool ProcessSpider(string line)
		{
			if (string.IsNullOrEmpty(line))
				throw new ArgumentNullException("line", "Cannot parse a null line");

			string[] lineparts = line.Split(' ');

			MV6DataContext dcMV6 = new MV6DataContext();

			// Find IP address
			IPAddress ipaddr;
			string ipstr = ExtractIPfromLogLine(lineparts);
			if (string.IsNullOrEmpty(ipstr)) return false;
			if (!IPAddress.TryParse(ipstr, out ipaddr)) return false;
			var ips = from i in dcMV6.IPs where i.Address == ipstr select i;
			if (ips.Count() == 0)
			{ // No such IP on record; insert
				DateTime trydate;
				if (!DateTime.TryParse(lineparts[0] + " " + lineparts[1], out trydate))
					trydate = DateTime.Now;
				IP ip = new IP();
				ip.Address = ipstr;
				ip.isSpider = true;
				ip.FirstAccess = trydate;
				ip.Hits = 1;
				ip.LastAccess = ip.FirstAccess;
				ip.Notes = "Inserted by META - Found in logs, missing from database";
				dcMV6.IPs.InsertOnSubmit(ip);
				KC.Logging.Logger.Write("META", "IP Address missing from SQL", "IPID " + ip.ID.ToString() + " not found in SQL, but found in IIS Logs.  The record was inserted successfully.", Logging.Logger.Severity.Warning);
			}
			else
			{ // IP exists; update
				foreach (IP ip in ips)
				{
					ip.isSpider = true;
					ip.Notes += "Flagged as spider by META " + DateTime.Now.ToString("MM/dd/yyyy");
				}
			}
			dcMV6.SubmitChanges();
			return true;
		}
	}
}
